/*
 * Timing function for the time out to Lock Window
 *
 * License: LGPL v3
 */

package org.passwordstore.util;

import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.Timer;
import org.passwordstore.Resource;

/*
 * @author thotheolh
 */
public class TimerAdapter implements Runnable, AWTEventListener {

    private int millisecond;
    private javax.swing.Timer timer;
    public final static long event = AWTEvent.KEY_EVENT_MASK + AWTEvent.MOUSE_MOTION_EVENT_MASK + AWTEvent.MOUSE_EVENT_MASK;

    public TimerAdapter(int minute) {
        this.millisecond = minute * 60000;
    }
    ActionListener taskPerformer = new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            //System.out.println("attempting lock screen...");//Diagnostics
            if (!Resource.getInstance().getMainInstance().isIsLocked()) {
                Resource.getInstance().getMainInstance().getMf().doLockWindow();
                //System.out.println("lock screen...");//Diagnostics
            }
        }
    };

    public void start() {// start timer
        if (timer == null) {
            timer = new Timer(millisecond, taskPerformer);
            Toolkit.getDefaultToolkit().addAWTEventListener(this, event);
        }
        timer.start();
    }

    public void stop() {// stop timer
        if (timer != null) {
            timer.stop();
            Toolkit.getDefaultToolkit().removeAWTEventListener(this);
        }
    }

    @Override
    public void run() {
        start();
    }

    @Override
    public void eventDispatched(AWTEvent awte) {
        if (timer.isRunning()) {
            timer.restart();
            //System.out.println("Actions detected... restart timer...");//Diagnostics
        }
    }
}
